from .view import AlertConfigure, AlertView
from . import schema
from typing import List
from fastapi import APIRouter, Depends, Security
from package.connector.sql_db import db
from package.fastapi import permission


router_alert = APIRouter(prefix='/alert', tags=['告警配置'])
router_meta = {'module': '数据分析', 'sub_module': '告警配置'}


@router_alert.get('/alert', response_model=schema.PageAlerts, openapi_extra=router_meta, name='alert_list_get',
                 summary='告警配置列表')
def alert_list_get(q: str = None,
             page: int = 1,
             page_size: int = 10,
             order_by: str = 'created_at desc',
             session=Depends(db.get_session),
             user=Security(permission.security, scopes=['alert:read'])):
    return AlertView.get_page_items(session, q=q, page=page, page_size=page_size, order_by=order_by)


@router_alert.post('/alert', response_model=schema.AlertOut, openapi_extra=router_meta, name='alert_post', summary='告警配置创建')
def alert_post(body: schema.CreateAlert,
              session=Depends(db.get_session),
              user=Security(permission.security, scopes=['alert:write'])):
    return AlertView.create_model(session, body=body.dict())


@router_alert.get('/alert/{id}', response_model=schema.AlertOut, openapi_extra=router_meta, name='alert_get',
                 summary='告警配置详情')
def alert_get(id: str,
             session=Depends(db.get_session),
             user=Security(permission.security, scopes=['alert:read'])):
    return AlertView.get_item(session, filter_=[AlertConfigure.id == id])


@router_alert.patch('/alert/{id}', response_model=schema.AlertOut, openapi_extra=router_meta, name='alert_patch',
                   summary='告警配置修改')
def alert_patch(id: str,
               body: schema.EditAlert,
               session=Depends(db.get_session),
               user=Security(permission.security, scopes=['alert:write'])):
    return AlertView.update_model(session, filter_=[AlertConfigure.id == id], update=body.dict(exclude_unset=True))


@router_alert.delete('/alert', openapi_extra=router_meta, name='alert_delete', summary='告警配置删除')
def alert_delete(body: schema.BatchId,
                session=Depends(db.get_session),
                user=Security(permission.security, scopes=['alert:write'])):
    return {'count': AlertView.delete_models(session, filter_=[AlertConfigure.id.in_(body.ids)])}
